import os
import pandas as pd
from zc_core.client.mongo_client import Mongo

meta_map = [
    {'col': '_id', 'title': '_id'},
    {'col': 'batchNo', 'title': '批次编号'},
    {'col': 'goodsType', 'title': '商品类型'},
    {'col': 'salePrice', 'title': '销售价'},
    {'col': 'originPrice', 'title': '原价'},
    {'col': 'brandName', 'title': '品牌'},
    {'col': 'catalogName', 'title': '分类名称'},
    {'col': 'catalogId', 'title': '分类id'},
    {'col': 'materialCode', 'title': '物料编码'},
    {'col': 'skuCode', 'title': '商品编码'},
    {'col': 'skuName', 'title': '商品名称'},
    {'col': 'statusName', 'title': '状态'},
    {'col': 'stock', 'title': '库存'}
]


def export_data(table, file, query={}):
    # 结构组装
    columns = list()
    headers = list()
    for meta in meta_map:
        columns.append(meta.get('col'))
        headers.append(meta.get('title'))

    # 数据查询
    rows = Mongo(mongo_db='plap_zc_deli_2021').list(
        collection=table,
        fields=columns,
        query=query,
        sort=[]
    )
    # print(rows)
    # 数据转换
    # for row in rows:
    #     row['publishTime'] = format_time(row.pop('publishTime'))
    #     row['deadlineTime'] = format_time(row.pop('deadlineTime'))
    #     row['validityDate'] = format_time(row.pop('validityDate'))

    # 写入Excel
    if rows:
        write = pd.ExcelWriter(file)
        df = pd.DataFrame(rows)
        df.to_excel(write, sheet_name='数据', columns=columns, header=headers, index=False)
        write.save()
        print('导出成功~')
    else:
        print('无数据~')


if __name__ == '__main__':
    bot_name = 'plap_zc_deli'
    batch_no = '20211122'
    dir = f'/work/{bot_name}'
    if not os.path.exists(dir):
        os.makedirs(dir)
    export_data(
        table='sku_{}'.format(batch_no),
        file=f'{dir}/军网_{batch_no}.xlsx',
    )
